package com.cuixk.controller;

import com.cuixk.entity.CacheBean;
import com.cuixk.entity.ChatContent;
import com.cuixk.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Create By Cuixk
 * 2018/10/17 17:39
 */
@Controller
public class ChatRoomController {

    @Autowired
    private SimpMessagingTemplate template;

    @MessageMapping("/talk")
    @SendTo("/refreshChatWindow")
    public ChatContent talk(ChatContent chatContent){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        chatContent.setDate(sdf.format(new Date()));
        return chatContent;
    }

    /**
     * 下线
     * @param user
     */
    @MessageMapping("/downLine")
    private void downLine(User user){
        List<User> list = CacheBean.clientList;
        list.remove(user);
        refreshLoginList();
    }


    /**
     * 服务器端通知客户端刷新当前登录人列表
     */
    @MessageMapping("/refreshLoginList")
    public void refreshLoginList(){
        template.convertAndSend("/refreshloginlist",CacheBean.clientList);
    }

    @MessageMapping("/onLine")
    private void onLine(User user){
        List<User> list = CacheBean.clientList;
        list.add(user);
        refreshLoginList();
    }
}
